package com.fluidops.datacatalog.reltables.schemacompare;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import com.fluidops.datacatalog.reltables.util.StringCompare;

public class SchemaMatcher {

	private StringCompare compare = new StringCompare();
	
	private double consistencyThreshold = 0.8d;
	
	public SchemaMatcher(){
		
	}
	public SchemaMatcher(double consistencyThreshold){
		this.consistencyThreshold = consistencyThreshold;
	}
	
	public boolean consistent(double val1 , double val2){
		double max = Math.max(Math.abs(val1), Math.abs(val2));
		if(max != 0){
			double sim = 1d - (Math.abs(val1 - val2) / max );
			return sim >= this.consistencyThreshold;
		}
		return true;
	}
	
	
	
	public double compareSchemas(Collection<String> a, Collection<String> b){
		if(a.isEmpty() || b.isEmpty()){
			return 0d;
		}
		double similiarity = 0;
		
		List<String> schemaA = new ArrayList<String>(a);
		List<String> schemaB = new ArrayList<String>(b);
		
		double max ;
		int maxIndex;
		
		String dimB;
		double currentSim;
		for(String dimA : schemaA){
			max = Double.MIN_VALUE; 
			maxIndex = -1;
			for(int i = 0; i < schemaB.size(); i++){
				dimB = schemaB.get(i);
				currentSim = this.compare.compareStrings(dimA, dimB);
				if(currentSim > max){
					max = currentSim;
					maxIndex = i;
					if(max == 1d){
						//1 is the maximum similarity score (identical strings)
						break;
					}
				}
			}
			if(maxIndex != -1){
				similiarity += max;
				schemaB.remove(maxIndex);
			}else{
				break;
			}
		}
		
		double n = Math.max(a.size(), b.size());
		
		return similiarity / n;
	}
	
	
	
}
